package cn.dankal.flyaudio.friend;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.kongzue.dialog.listener.InputDialogOkButtonClickListener;
import com.kongzue.dialog.v2.InputDialog;
import com.kongzue.dialog.v2.TipDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureSelectionConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.GlideApp;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.camera.CameraHandlerTow;
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer;
import cn.dankal.basiclib.template.personal.ChangeAvatar;
import cn.dankal.basiclib.template.personal.ChangeAvatarImpl;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.R;
import cn.flyaudio.phonecontrol.mycar.util.GlideUtil;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetGroupInfoCallback;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.api.BasicCallback;

public class GroupManagerActivity extends BaseActivity implements View.OnClickListener {

    private static final int SETNAME_REQUESTCODE = 205;


    private TextView groupNameView;

    private ImageView avatarView;
    private GroupInfo groupInfo;
    private boolean isOwner = false;
    private ChangeAvatar changeAvatar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_manager;
    }

    @Override
    protected void initComponents() {
        addSingleTitleBar("群管理");
        groupNameView = findViewById(R.id.tv_group_name);
        avatarView = findViewById(R.id.iv_avatar);
        long groupId = getIntent().getLongExtra("group_id", 0);
        isOwner = getIntent().getBooleanExtra("isGroupManager", false);
        findViewById(R.id.rl_update_group_name).setOnClickListener(this);
        findViewById(R.id.rl_update_group_owner).setOnClickListener(this);
        findViewById(R.id.iv_avatar).setOnClickListener(this);
        JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
            @Override
            public void gotResult(int i, String s, GroupInfo groupInfo) {
                Log.d("GroupManagerActivity", "群信息获取:" + s);
                initGroupData(groupInfo);
            }
        });
        changeAvatar = new ChangeAvatarImpl(this, this);
        changeAvatar.setIvHead(avatarView);

    }

    private void initGroupData(GroupInfo groupInfo) {
        this.groupInfo = groupInfo;
        groupNameView.setText(groupInfo.getGroupName());
//        GlideApp.with(this).load(groupInfo.getAvatar())
//                .into(avatarView);
//        groupInfo.getAvatarFile().getParent()
        PicUtils.loadAvatarByGroup(groupInfo.getAvatarFile(), avatarView);
//        RequestOptions options = new RequestOptions()
//                .placeholder(R.mipmap.ic_default_avatar)
//                .error(R.mipmap.ic_default_avatar)
//                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
//                .skipMemoryCache(false)
//                .dontAnimate()
//                .transform(transformation);
////        if (transformation != null) {
//            options.transform(transformation)
//        }
//        GlideApp.with(this).load(groupInfo.getAvatarFile()).placeholder().into(avatarView);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_update_group_name:
                if (!isOwner) {
                    TipDialog.show(GroupManagerActivity.this, "您不是群主，无法修改群名称");
                    return;
                }
                InputDialog.show(GroupManagerActivity.this, "提示", "请输入群名称", "确定", new InputDialogOkButtonClickListener() {
                    @Override
                    public void onClick(Dialog dialog, String inputText) {
                        if (TextUtils.isEmpty(inputText.trim())) {
                            ToastUtils.showShort("群名称不能为空!");
                            return;
                        }
                        groupInfo.updateName(inputText, new BasicCallback() {
                            @Override
                            public void gotResult(int i, String s) {
                                groupNameView.setText(inputText);
                                dialog.dismiss();
                            }
                        });
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
            case R.id.rl_update_group_owner:
                Intent intent = new Intent(this, ChangeGroupOwnerActivity.class);
                intent.putExtra("group_id", groupInfo.getGroupID());
                startActivity(intent);
                break;
            case R.id.iv_avatar:
                AliUIDisplayer aliUIDisplayer = new AliUIDisplayer(avatarView, this, null);
                changeAvatar.checkPermission(new CameraHandlerTow(this));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片、视频、音频选择结果回调
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);

        if (selectList != null && selectList.size() > 0) {
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
            // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
            if (selectList != null && selectList.size() > 0) {
                setImage(selectList);
                return;
            }
            String outPutCamera = Environment.getExternalStorageDirectory().getAbsolutePath() + PictureSelectionConfig.getInstance().cameraPath;
            Log.d("GroupManager", outPutCamera);
            if (!TextUtils.isEmpty(outPutCamera)) {
                setImage(outPutCamera);
            }
        }
    }

    private void setImage(String list) {
        try {
            //uploadImage = UIUtils.compressImage(UIUtils.getBitmapFromUrl(path, 200, 200))
            Uri uri = Uri.parse(list);
            groupInfo.updateAvatar(new File(list), list, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    ToastUtils.showShort("修改成功");
                }
            });
            GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(list).into(new BitmapImageViewTarget(avatarView) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    avatarView.setImageDrawable(circularBitmapDrawable);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setImage(List<LocalMedia> list) {
        LocalMedia media = list.get(0);
        String mimeType = media.getMimeType();
        String path = "";
        //Android Q 特有Path:
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
//                                upload(new File(media.getAndroidQToPath()));
            path = media.getAndroidQToPath();
        } else {
            if (media.isCompressed()) {
                //是否压缩
//                                    upload(new File(media.getCompressPath()));
                path = media.getCompressPath();
            } else {
                if (media.isOriginal()) {
                    //是否开启原图
//                                        upload(new File(media.getOriginalPath()));
                    path = media.getOriginalPath();
                } else {
//                                        upload(new File(media.getPath()));
                    path = media.getPath();
                }
            }
        }
        // 图片
        if (media.isCompressed()) {
            Log.i("compress image result:", (new File(media.getCompressPath()).length() / 1024) + "k");
            Log.i("压缩地址::", media.getCompressPath());
        }

        Log.i("原图地址::", media.getPath() + "-----" + media.isCompressed() + "---" + path);
        //int pictureType = PictureMimeType.isPictureType(media.getPictureType());
        if (media.isCut()) {
            Log.i("裁剪地址::", media.getCutPath());
        }
        try {
            //uploadImage = UIUtils.compressImage(UIUtils.getBitmapFromUrl(path, 200, 200))
            Uri uri = Uri.parse(path);
            File file = new File(path);
            groupInfo.updateAvatar(file, path, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    ToastUtils.showShort("修改成功");
                }
            });
            GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(path).into(new BitmapImageViewTarget(avatarView) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    avatarView.setImageDrawable(circularBitmapDrawable);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
